<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-24
 * Time: 16:45
 */
namespace App\Http\Middleware;

use Auth;
use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class RefreshToken extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
     *
     * @return mixed
     */
    public function handle($request, Closure $next,$guard=null)
    {
        // 检查此次请求中是否带有 token，如果没有则抛出异常。
        $this->checkForToken($request);


        // 使用 try 包裹，以捕捉 token 过期所抛出的 TokenExpiredException  异常
        try {
            // 检测用户的登录状态，如果正常则通过
            if ($this->auth->parseToken()->check()) {
                $foo = auth()->payload()->get('foo');

                if($guard != $foo){
                    return response()->json(['code'=>'-1','message'=>'您无权限进行此操作']);
                }

                $user = auth()->guard($foo)->user();
                if(empty($user)){
                    throw new UnauthorizedHttpException('jwt-auth', '登录失效');
                }

                $uid_params = $this->setUser($foo,$user);
                $request->merge($uid_params);//合并参数
                return $next($request);
            }
            throw new UnauthorizedHttpException('jwt-auth', '未登录');
        } catch (TokenExpiredException $exception) {

            // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常，我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中
            try {
                $foo = auth()->payload()->get('foo');
                if($guard != $foo){
                    return response()->json(['code'=>'-1','message'=>'您无权限进行此操作']);
                }

                // 刷新用户的 token
                $token = auth($foo)->refresh();

                // 使用一次性登录以保证此次请求的成功
                Auth::guard($foo)->onceUsingId(auth($foo)->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
            } catch (JWTException $exception) {
                // 如果捕获到此异常，即代表 refresh 也过期了，用户无法刷新令牌，需要重新登录。
                throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
            }
        }

        $user = auth()->guard($foo)->user();
        if(empty($user)){
            throw new UnauthorizedHttpException('jwt-auth', '登录失效');
        }
        $uid_params = $this->setUser($foo,$user);
        $request->merge($uid_params);//合并参数

        // 在响应头中返回新的 token
        return $this->setAuthenticationHeader($next($request), $token);
    }

    protected function setUser($guard,$user)
    {
        $temp = [];
        if($guard == 'admin'){
            $temp['user'] = ['guard'=>'admin','admin_uid'=>$user->id,'member_uid'=>0,'uid'=>$user->id];
        }else{
            $temp['user'] = ['guard'=>'member','member_uid'=>$user->id,'admin_uid'=>0,'uid'=>$user->id];
        }

        return $temp;
    }
}
